{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1bf704c1",
   "metadata": {},
   "source": [
    "# 千帆大模型API调用代码模板\n",
    "\n",
    "同济子豪兄 2023-10-24"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bc21408",
   "metadata": {},
   "source": [
    "## 导入工具包"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "df95d1e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "901191df",
   "metadata": {},
   "source": [
    "## 传入API Key、Secret Key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5f1d5a28",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'YEeltK****wdjhHq'\n",
    "SECRET_KEY = 'v3W9rN****KYGspR'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e9e8e23",
   "metadata": {},
   "source": [
    "## 使用 AK，SK 生成鉴权签名（Access Token）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "12f9d807",
   "metadata": {},
   "outputs": [],
   "source": [
    "url = \"https://aip.baidubce.com/oauth/2.0/token\"\n",
    "params = {\"grant_type\": \"client_credentials\", \"client_id\": API_KEY, \"client_secret\": SECRET_KEY}\n",
    "access_token = str(requests.post(url, params=params).json().get(\"access_token\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0b6dc207",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.b933b8b52b8ec02ddd6b2cb4d807d28b.2592000.1700491335.282335-41296247'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed427aa5",
   "metadata": {},
   "source": [
    "## 构造多轮对话提示词（消息数量必须是奇数，因为一问一答，要等AI完成回答）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b5313446",
   "metadata": {},
   "outputs": [],
   "source": [
    "payload = json.dumps({\n",
    "    \"messages\": [\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"你好，请问你是哪家公司开发的大模型\"\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"assistant\",\n",
    "            \"content\": \"你好，我是百度公司开发的大模型，我的中文名是文心一言，英文名是ERNIE Bot。我可以协助您完成范围广泛的任务并提供有关各种主题的信息，比如回答问题，提供定义和解释及建议。如果您有任何问题，请随时向我提问。\"\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"你们公司的人工智能产品还有哪些\"\n",
    "        }\n",
    "    ]\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce8c8053",
   "metadata": {},
   "source": [
    "## 选择千帆大模型平台上的大模型（任选一个即可）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c747b3ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 文心大模型 4.0\n",
    "url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=\" + access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4265f536",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Qianfan-Chinese-Llama-2-7b\n",
    "# url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/qianfan_chinese_llama_2_7b?access_token=\" + access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c52fb0c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Llama-2-7b-Chat\n",
    "# url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/llama_2_7b?access_token=\" + access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a3ed591e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Llama-2-70b-Chat\n",
    "# url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/llama_2_70b?access_token=\" + access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "f3354374",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # BLOOMZ-7B\n",
    "# url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/bloomz_7b1?access_token=\" + access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4e311ebd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # ChatGLM2-6B\n",
    "# url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/chatglm2_6b_32k?access_token=\" + access_token"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "becbd7d5",
   "metadata": {},
   "source": [
    "## 调用API，发起请求"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "bdc89efe",
   "metadata": {},
   "outputs": [],
   "source": [
    "headers = {\n",
    "    'Content-Type': 'application/json'\n",
    "}\n",
    "\n",
    "response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "\n",
    "response = json.loads(response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30b4afe9",
   "metadata": {},
   "source": [
    "## 获取调用结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "8eb50c32",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'id': 'as-dmnc1vqfun',\n",
       " 'object': 'chat.completion',\n",
       " 'created': 1697702550,\n",
       " 'result': '百度的人工智能产品有很多，除了文心一言之外，还有如下产品：\\n\\n1. 百度大脑：百度自主研发的全球最大规模的人工智能开放平台，旨在为开发者提供强大、稳定、可靠的AI能力。\\n2. 百度智能云：百度提供的一站式云计算服务，利用人工智能技术，为企业提供高效、安全的计算服务。\\n3. 小度助手：百度推出的智能语音助手，通过与用户进行语音交互，实现各种智能操作。\\n\\n除此之外，百度还涉足了智能驾驶、智能家居等领域，推出了百度Apollo、小度智能家居等产品。这些产品充分展示了百度在人工智能领域的领先地位和广泛的应用前景。',\n",
       " 'is_truncated': False,\n",
       " 'need_clear_history': False,\n",
       " 'usage': {'prompt_tokens': 119,\n",
       "  'completion_tokens': 215,\n",
       "  'total_tokens': 334}}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "076eee4e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'百度的人工智能产品有很多，除了文心一言之外，还有如下产品：\\n\\n1. 百度大脑：百度自主研发的全球最大规模的人工智能开放平台，旨在为开发者提供强大、稳定、可靠的AI能力。\\n2. 百度智能云：百度提供的一站式云计算服务，利用人工智能技术，为企业提供高效、安全的计算服务。\\n3. 小度助手：百度推出的智能语音助手，通过与用户进行语音交互，实现各种智能操作。\\n\\n除此之外，百度还涉足了智能驾驶、智能家居等领域，推出了百度Apollo、小度智能家居等产品。这些产品充分展示了百度在人工智能领域的领先地位和广泛的应用前景。'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response['result']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f863a2e8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
